import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Input, Select, Button, Table, Modal, Pagination, message } from 'antd';
import { DEFAULT_PAGE_SIZE, DEFAULT_VALID_STATE } from '@/constants';
import { CONST_PERMISSION_CODE_STAFF_ADD, CONST_PERMISSION_CODE_STAFF_UPD, CONST_PERMISSION_CODE_STAFF_STOP, CONST_PERMISSION_CODE_STAFF_DOWNLOAD, CONST_PERMISSION_CODE_STAFF_UPLOAD } from '@/constants';
import styles from './index.less';

import Edit from './edit';
import HandleFile from './Common/HandleFile';
import UnitDepartment from '../Organization/Common/UnitDepartment';

const { Sider, Content } = Layout;
const { confirm } = Modal;
const { Option } = Select;

const CONST_MODE_SELECT = 'select';
const CONST_MODE_LIST = 'list';

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'staff';
    const { global, location = {}, currentUnit, mode } = props;
    const { pathname } = location;
    console.log("currentUnit",global.currentUnit);
    this.state = {
      currentUnitName: currentUnit ? currentUnit.unit_name : global.currentUnit && pathname !== '/addressBook' ? global.currentUnit.unit_name : '',
      constants: {
        genders: [],
        ranks: [],
        units: [],
        departments: []
      },
      query: {
        active: DEFAULT_VALID_STATE,
        unit_id: {
          id: currentUnit && currentUnit.id ? currentUnit.id : (global.currentUnit && global.currentUnit.id && pathname !== '/addressBook' ? global.currentUnit.id : -1)
        }
      },
      mode: mode || CONST_MODE_LIST
    }
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/queryConfigDictionary',
      payload: {
        code: 'GENDER',
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, genders: data } });
        }
      }
    });
    this.props.dispatch({
      type: 'global/queryRank',
      payload: {
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, ranks: data } });
        }
      }
    });
    this.props.dispatch({
      type: `unit/queryData`,
      payload: {
        state: DEFAULT_VALID_STATE,
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, units: data } });
        }
      }
    });
    this.props.dispatch({
      type: `department/queryData`,
      payload: {
        state: DEFAULT_VALID_STATE,
        unit_id: this.state.query.unit_id,
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, departments: data } });
        }
      }
    });
    this.queryData(1, this.state.mode === CONST_MODE_LIST ? DEFAULT_PAGE_SIZE : DEFAULT_PAGE_SIZE / 2);
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  appendBtnClick = () => {
    const { query = {} } = this.state;

    if (query.unit_id.id && query.unit_id.id !== -1) {
      this.props.dispatch({
        type: `${this.modularName}/changeState`,
        payload: { visible: '新增人员', editData: {} }
      });
    } else {
      message.error('请选择要新增人员的单位', 2);
    }
  }

  detailBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '查看人员', editData: record }
    });
  }

  editBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑人员', editData: record }
    });
  }

  stopBtnClick = (record) => {
    confirm({
      title: '是否确认删除人员?',
      content: Array.isArray(record) ? undefined : `人员 [${record.name}]`,
      onOk: () => {
        const { query = {} } = this.state;
        const { dispatch, modular } = this.props;
        const { current, pageSize } = modular;

        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            ids: Array.isArray(record) ? record.map(item => item.id) : [record.id],
            ...query,
            current,
            pageSize
          }
        });
      },
      onCancel() { },
    });
  }

  searchBtnClick = () => {
    const { modular } = this.props;
    const { pageSize = DEFAULT_PAGE_SIZE } = modular;

    this.queryData(1, pageSize);
  }

  handleFile = () => {
    const { query = {} } = this.state;

    if (query.unit_id.id && query.unit_id.id !== -1) {
      this.props.dispatch({
        type: `${this.modularName}/changeState`,
        payload: { visible: '导入/导出', editData: {} }
      });
    } else {
      message.error('请选择要导入/导出人员数据的单位', 2);
    }
  }

  onChange = (current, pageSize) => {
    this.queryData(current, pageSize);
  }

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize)
  }

  onOk = () => {
    const { query = {} } = this.state;
    const { dispatch, form, modular } = this.props;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const { phone_is_secrecy, telphone, family_phone, rank, ...extra } = values
        const { user_name, user_duty, active, deptname, rankname, roles, ...extraData } = editData;

        dispatch({
          type: `${this.modularName}/saveOrUpdateData`,
          payload: {
            data: {
              id: editData.id,
              ...extra,
              telphone: telphone ? Array.isArray(telphone) ? telphone.filter(item => item).join('-') : telphone : undefined,
              family_phone: family_phone ? Array.isArray(family_phone) ? family_phone.filter(item => item).join('-') : family_phone : undefined,
              phone_is_secrecy: typeof phone_is_secrecy === 'number' ? phone_is_secrecy : phone_is_secrecy ? 1 : 0,
              rank: typeof rank === 'string' ? rank : rank ? (rank + '') : undefined
            },
            ...query,
            current,
            pageSize
          }
        });
      }
    })
  }

  onTreeSelect = (id, name, type) => {
    if (type === 'unit') {
      const { query = {} } = this.state;
      const { modular } = this.props;
      const { pageSize = DEFAULT_PAGE_SIZE } = modular;

      this.props.dispatch({
        type: `department/queryData`,
        payload: {
          state: DEFAULT_VALID_STATE,
          unit_id: id || -1,
          current: 1,
          pageSize: 10000,
          callback: (data = []) => {
            this.setState({ constants: { ...this.state.constants, departments: data } });
          }
        }
      });
      this.setState({ currentUnitName: name || '', query: { ...query, user_dept: undefined, unit_id: { id: id || -1 } } }, () => {
        this.queryData(1, pageSize);
      });
    }
  }

  queryData = (current, pageSize) => {
    const { query = {} } = this.state;
    const { dispatch, location = {}, queryMethod } = this.props;
    const { pathname } = location;

    dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current,
        pageSize,
        method: pathname === '/addressBook' || queryMethod === 'addressBook' ? 'communicationQuery' : undefined
      }
    });
  }

  render() {
    const { constants = {}, currentUnitName, query = {}, selectedRows = [], mode } = this.state;
    const { genders = [], ranks = [], units = [], departments = [] } = constants;
    const { dispatch, form, loading, location = {}, global, modular, queryMethod } = this.props;
    const { isAdmin, userPermissions = [] } = global;
    const { data, current = 1, pageSize = DEFAULT_PAGE_SIZE, total = 0, rowKey, visible, editData = {} } = modular;
    const { pathname } = location;

    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        ellipsis: true,
        width: 200,
        fixed: 'left'
      },
      {
        title: '值班部门',
        dataIndex: 'unitname',
        ellipsis: true,
        width: 200
      },
      {
        title: '部门',
        dataIndex: 'deptname',
        ellipsis: true,
        width: 200
      },
      {
        title: '性别',
        dataIndex: 'user_age',
        ellipsis: true,
        width: 200,
        render: (text, record) => {
          return <span>{text == "0" ? "女" : "男"}</span>
        }
      },
      {
        title: '职务',
        dataIndex: 'user_duty',
        ellipsis: true,
        width: 200
      },
      {
        title: '办公电话',
        dataIndex: 'telphone',
        ellipsis: true,
        width: 200,
        render: (text, record) => {
          if (text) {
            try {
              const array = text.split('-');
              return array.filter(item => item && item.trim()).join('-');
            } catch (e) {
              console.error(e);
            }
          }
          return text;
        }
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        ellipsis: true,
        width: 200
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.detailBtnClick.bind(this, record)}>查看</span>
              {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_UPD) &&
                <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
              }
              {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_STOP) &&
                <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>删除</span>
              }
            </div>
          );
        }
      }
    ];

    return (
      <Layout className={styles.basic_layout_wrapper}>
        {(mode === CONST_MODE_LIST && isAdmin || pathname === '/addressBook') &&
          <Sider
            className={styles.sider_wrapper}
            style={{
              overflow: 'hidden',
              position: 'fixed',
              // left: 24,
            }}
            width={256}
          >
            <div>
              <UnitDepartment hasChild={false} loading={!!loading.effects[`unit/queryData`]} units={units} currentId={query.unit_id.id} onTreeSelect={this.onTreeSelect} />
            </div>
          </Sider>
        }
        <Layout style={{ ...this.props.style, marginLeft: (mode === CONST_MODE_LIST && isAdmin || pathname === '/addressBook') ? 256 : 0 }}>
          {mode === CONST_MODE_LIST &&
            <div className={styles.title}>
              当前单位: <span style={{ color: 'rgb(27, 139, 236)' }}>{currentUnitName}</span>
            </div>
          }
          <div className={[styles.conditions_wrapper, mode === CONST_MODE_SELECT ? styles.conditions_no_border_wrapper : null].join(' ')}>
            <Input placeholder='姓名' style={{ width: 240, marginRight: 16 }} onChange={e => this.setState({ query: { ...query, name: e.target.value || undefined } })} />
            {/* <Select
              allowClear
              placeholder='职级'
              showSearch
              style={{ width: 240, marginRight: 16 }}
              filterOption={(input, option) => {
                return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }}
            >
              {ranks && ranks.map(item => {
                return <Option key={item.id} value={item.id}>{item.rank_name}</Option>
              })}
            </Select> */}
            {queryMethod === 'addressBook' ?
              <Select
                allowClear
                placeholder='单位'
                showSearch
                style={{ width: 240, marginRight: 16 }}
                filterOption={(input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
                value={query.unit_id.id !== -1 ? query.unit_id.id : undefined}
                onChange={value => this.setState({ query: { ...query, unit_id: { id: value } } })}
              >
                {units && units.map(item => {
                  return <Option key={item.id} value={item.id}>{item.unit_name}</Option>
                })}
              </Select> :
              <Select
                allowClear
                placeholder='部门'
                showSearch
                style={{ width: 240, marginRight: 16 }}
                filterOption={(input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
                value={query.user_dept}
                onChange={value => this.setState({ query: { ...query, user_dept: value } })}
              >
                {departments && departments.map(item => {
                  return <Option key={item.id} value={item.id}>{item.dept_name}</Option>
                })}
              </Select>
            }
            <Button icon='search' type='primary' style={{ marginRight: 16 }} onClick={this.searchBtnClick}>搜索</Button>
            {this.props.toolExtra}
          </div>
          <Content className={[styles.conditions_wrapper, mode === CONST_MODE_SELECT ? styles.conditions_no_border_wrapper : null].join(' ')} style={{ margin: 0 }}>
            <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
              {mode === CONST_MODE_LIST && pathname !== '/addressBook' &&
                <div>
                  {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_ADD) &&
                    <Button icon='plus' type='primary' style={{ width: 110, marginRight: 16, marginBottom: 16 }} onClick={this.appendBtnClick}>新增</Button>
                  }
                  {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_STOP) &&
                    <Button icon='delete' type='danger' style={{ marginRight: 16, marginBottom: 16 }} onClick={selectedRows && selectedRows.length > 0 ? this.stopBtnClick.bind(this, selectedRows) : undefined}>批量删除{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
                  }
                  {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_DOWNLOAD) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_UPLOAD) &&
                    <Button icon='thunderbolt' style={{ marginBottom: 16 }} onClick={this.handleFile}>导入/导出</Button>
                  }
                </div>
              }
              <Content className={styles.common_table_wrapper}>
                <Table
                  columns={mode === CONST_MODE_LIST && pathname !== '/addressBook' ? columns : columns.slice(0, columns.length - 1)}
                  dataSource={data}
                  loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                  pagination={false}
                  rowKey={rowKey}
                  rowSelection={
                    Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_STAFF_STOP) && mode === CONST_MODE_LIST && pathname !== '/addressBook' ?
                      {
                        onChange: (selectedRowKeys, rows) => {
                          this.setState({ selectedRows: [...selectedRows.filter(item => selectedRowKeys.includes(item.id) && !rows.map(row => row.id).includes(item.id)), ...rows] })
                        }
                      } :
                      null
                  }
                  scroll={{ x: true }}
                  {...this.props.tableOptions}
                />
              </Content>
              <div style={{ marginTop: 16 }}>
                <Pagination
                  current={current}
                  pageSize={pageSize}
                  total={total}
                  showQuickJumper
                  showSizeChanger={mode === CONST_MODE_LIST}
                  showTotal={(total, range) => `共有 ${total} 条数据`}
                  onChange={this.onChange}
                  onShowSizeChange={this.onShowSizeChange}
                />
              </div>
            </Layout>
          </Content>
        </Layout>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={visible === '导入/导出' ? 960 : 560}
          okButtonProps={visible === '导入/导出' || visible === '查看人员' ? { style: { display: 'none' } } : {}}
          cancelButtonProps={visible === '导入/导出' ? { style: { display: 'none' } } : {}}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            })
          }}
        >
          {visible === '导入/导出' ?
            <HandleFile dispatch={dispatch} loading={loading} modularName={this.modularName} currentUnit={{ id: query.unit_id.id, unit_name: currentUnitName }} /> :
            <Edit
              dispatch={dispatch}
              form={form}
              modularName={this.modularName}
              constants={constants}
              currentUnit={{ id: query.unit_id.id, unit_name: currentUnitName }}
              data={editData}
              unitAddress={global.currentUnit.unit_address}
              unit_phone={global.currentUnit.unit_phone}
              disabled={visible === '查看人员'}
            />
          }
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, global, staff }) => ({ loading, global, modular: staff }))(Form.create()(Index));